import React from 'react'

export default function ShoppingCartHeader({ cartList, deleteCartList }) {
    const list = cartList.current;

    const handleDelete = (e) => {
        deleteCartList(e.target.dataset.id);
    }

    const handleBuy = () => {
        let sum = 0;
        list.forEach(item => {
            sum += item.num * item.price;
        })
        alert(sum.toFixed(2))
    }

    return <div className="wind-cart-header">
        <div className="title">购物天堂</div>
        <div className="hover-wrap">
            <button className="wind-hover-cart">购物车</button>
            {list.length > 0 && <div className="wind-cart">
                {
                    list.map(({ title, num, price, id }) => {
                        return <CardList
                            key={title}
                            title={title}
                            num={num}
                            price={price}
                            id={id}
                            handleDelete={handleDelete}
                        ></CardList>
                    })
                }
                <button className="buy-btn" onClick={handleBuy}>购买</button>
            </div>}
        </div>
    </div>
}

function CardList({ title, num, price, id, handleDelete }) {
    return <div className="cart-list">
        <div className="name" title={title}>{title}</div>
        <div className="info">{price}*{num}</div>
        <button className="btn" data-id={id} onClick={handleDelete}>删除</button>
    </div>
}